
import React, { useState, useEffect } from 'react';
import { GroupName } from '../types.ts';

interface WheelProps {
  isSpinning: boolean;
  result: GroupName | null;
  groups: string[];
}

// 动态计算每个组的起始角度和中心角度
const getGroupAngles = (groups: string[]) => {
  const anglePerGroup = 360 / groups.length;
  const startAngles: { [key: string]: number } = {};
  const centerAngles: { [key: string]: number } = {};

  groups.forEach((group, index) => {
    startAngles[group] = index * anglePerGroup;
    centerAngles[group] = index * anglePerGroup + anglePerGroup / 2;
  });

  return { startAngles, centerAngles };
};

const Wheel: React.FC<WheelProps> = ({ isSpinning, result, groups }) => {
  const [rotation, setRotation] = useState(0);

  // 动态计算组角度
  const { centerAngles } = getGroupAngles(groups);

  useEffect(() => {
    if (isSpinning && result) {
      // 根据后台返回的结果，转盘停止在对应组的中心位置
      let targetAngleOnWheel = centerAngles[result];

      // 如果结果不在当前组别中，随机选择一个组别
      if (targetAngleOnWheel === undefined) {
        const randomGroupIndex = Math.floor(Math.random() * groups.length);
        const randomGroup = groups[randomGroupIndex];
        targetAngleOnWheel = centerAngles[randomGroup];
        console.log(`结果 ${result} 不在转盘组别中，随机选择 ${randomGroup} 组进行动画`);
      }

      // 计算需要转动的角度，使目标角度对准顶部指针
      // 由于指针在顶部（0度位置），我们需要将目标角度转到顶部
      const stoppingPointAngle = 360 - targetAngleOnWheel;

      // 添加多圈转动以增加视觉效果（5-7圈，确保足够的转动时间）
      const randomSpins = Math.floor(Math.random() * 3) + 5;

      // 计算最终转动角度
      const currentFullCircles = Math.floor(rotation / 360);
      const newRotation = (currentFullCircles + randomSpins) * 360 + stoppingPointAngle;

      console.log(`转盘转动到 ${result} 组，目标角度: ${targetAngleOnWheel}°，最终转动: ${newRotation}°`);
      setRotation(newRotation);
    }
  }, [isSpinning, result, rotation, centerAngles, groups]);
  
  const transitionStyle = isSpinning
    ? 'transform 4s cubic-bezier(0.25, 1, 0.5, 1)' // Ease-out for a smooth stop
    : 'none';

  // Helper to position labels trigonometrically
  const getLabelPosition = (angle: number) => {
      const radius = 38; // % from center
      const radian = (angle * Math.PI) / 180;
      const x = 50 + radius * Math.sin(radian);
      const y = 50 - radius * Math.cos(radian);
      return { top: `${y}%`, left: `${x}%` };
  };

  // 生成动态颜色渐变
  const generateConicGradient = (groups: string[]) => {
    const colors = ['#dc2626', '#3b82f6', '#22c55e', '#f59e0b', '#8b5cf6', '#ef4444', '#06b6d4', '#84cc16'];
    const anglePerGroup = 360 / groups.length;

    let gradientStops: string[] = [];
    groups.forEach((group, index) => {
      const startAngle = index * anglePerGroup;
      const endAngle = (index + 1) * anglePerGroup;
      const color = colors[index % colors.length];

      gradientStops.push(`${color}_${startAngle}deg`);
      gradientStops.push(`${color}_${endAngle}deg`);
    });

    return `conic-gradient(${gradientStops.join(',')})`;
  };

  return (
    <div
      className="relative w-64 h-64 md:w-80 md:h-80 flex items-center justify-center"
      style={{
        touchAction: 'none', // 防止移动端触摸滚动
        userSelect: 'none', // 防止选择文本
      }}
    >
      {/* The rotating part: Color wheel, labels, and center hub */}
      <div
        className="absolute w-full h-full"
        style={{
          transform: `rotate(${rotation}deg)`,
          transition: transitionStyle,
          touchAction: 'none', // 防止移动端触摸滚动
          userSelect: 'none', // 防止选择文本
        }}
      >
        <div className="relative w-full h-full rounded-full border-8 border-slate-700/80 shadow-2xl overflow-hidden">
          {/* 动态生成扇形区域 */}
          {groups.map((group, index) => {
            const colors = ['#dc2626', '#3b82f6', '#22c55e', '#f59e0b', '#8b5cf6', '#ef4444', '#06b6d4', '#84cc16'];
            const anglePerGroup = 360 / groups.length;
            const startAngle = index * anglePerGroup;
            const endAngle = (index + 1) * anglePerGroup;
            const color = colors[index % colors.length];

            // 创建扇形路径
            const centerX = 50;
            const centerY = 50;
            const radius = 50;

            const startAngleRad = (startAngle * Math.PI) / 180;
            const endAngleRad = (endAngle * Math.PI) / 180;

            const x1 = centerX + radius * Math.cos(startAngleRad - Math.PI / 2);
            const y1 = centerY + radius * Math.sin(startAngleRad - Math.PI / 2);
            const x2 = centerX + radius * Math.cos(endAngleRad - Math.PI / 2);
            const y2 = centerY + radius * Math.sin(endAngleRad - Math.PI / 2);

            const largeArcFlag = anglePerGroup > 180 ? 1 : 0;

            const pathData = [
              `M ${centerX} ${centerY}`,
              `L ${x1} ${y1}`,
              `A ${radius} ${radius} 0 ${largeArcFlag} 1 ${x2} ${y2}`,
              'Z'
            ].join(' ');

            return (
              <svg
                key={`sector-${group}`}
                className="absolute inset-0 w-full h-full"
                viewBox="0 0 100 100"
              >
                <path
                  d={pathData}
                  fill={color}
                  stroke="white"
                  strokeWidth="0.5"
                />
              </svg>
            );
          })}

          {/* 动态生成标签 */}
          {groups.map((group, index) => {
            const { centerAngles } = getGroupAngles(groups);
            return (
              <span
                key={group}
                className="absolute text-4xl md:text-5xl font-bold text-white -translate-x-1/2 -translate-y-1/2 drop-shadow-lg z-10"
                style={getLabelPosition(centerAngles[group])}
              >
                {group}
              </span>
            );
          })}

          {/* Center Hub */}
          <div className="absolute top-1/2 left-1/2 w-16 h-16 -translate-x-1/2 -translate-y-1/2 bg-slate-800 rounded-full border-4 border-slate-600 shadow-inner z-20"></div>
        </div>
      </div>

      {/* The static part: Pointer only */}
      <div className="absolute w-full h-full pointer-events-none">
          {/* Pointer */}
          <div className="absolute -top-3 left-1/2 -translate-x-1/2 w-0 h-0 border-l-[18px] border-l-transparent border-r-[18px] border-r-transparent border-t-[30px] border-t-yellow-400 z-20 drop-shadow-[0_2px_2px_rgba(0,0,0,0.5)]"></div>
      </div>
    </div>
  );
};

export default Wheel;
